#!/usr/bin/env python
# -*- coding:utf-8 -*-
from datetime import datetime

from conn.MyLogs import MyLogs
from hcmv.beans.SubjectMesObj import SubjectMesObj


class WebSubjetService:
    std_array = {}
    conn = None

    def __init__(self, conn):
        self.conn = conn

    def fetch_subject(self, param):
        try:
            count_sql = f" SELECT count(`id`) FROM `mem_subject_advice` WHERE 1=1 %s"
            fetch_sql = f" SELECT * " \
                        f" FROM `mem_subject_advice` WHERE 1=1 %s "
            where_sql = ""
            if len(param['key']) > 0:
                where_sql = where_sql + f" AND CONCAT(`create_time`) like CONCAT('%',\'{param['key']}\','%') "
            int_begin = 0
            if int(param['pageNum']) > 1:
                int_begin = (int(param['pageNum']) - 1) * int(param['pageSize'])
            elif int(param['pageNum']) == 1:
                int_begin = 0 * int(param['pageSize'])
            where_sql_no_limit = where_sql + f" ORDER BY `create_time` DESC"
            where_sql_limit = where_sql_no_limit + f" LIMIT {int_begin}, {int(param['pageSize'])}"
            data_total = self.conn.sql_fetch(count_sql % where_sql_no_limit)
            data_list = self.conn.sql_fetch(fetch_sql % where_sql_limit)
            items = []
            if len(data_list) > 0:
                items = [SubjectMesObj.load_db_2_dict(data=item) for item in data_list]
            return {"code": 200, "data": items, "total": data_total[0][0]}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def subject_message(self, subject):
        try:
            insert_sql = f" INSERT INTO `mem_subject_advice` ({SubjectMesObj.to_string(False)}) " \
                         " VALUES ( %s )" % SubjectMesObj.concat_datas(subject)
            self.conn.sql_commit(insert_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def read_message(self, id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = self.count_one(id=id)
        if not add_check:
            return {"code": 404, "data": None}
        execute_SQL = f" UPDATE `mem_subject_advice` SET " \
                      f" `status` = \'{SubjectMesObj.READ_STATUS['READ']}\'," \
                      f" `reply_time`=\'{current_time}\'" \
                      f" WHERE `id` = \'{id}\'"
        self.conn.sql_commit(execute_SQL)
        return {"code": 200, "data": None}

    def drop_message(self, id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = self.count_one(id=id)
        if not add_check:
            return {"code": 404, "data": None}
        execute_SQL = f" UPDATE `mem_subject_advice` SET " \
                      f" `status` = \'{SubjectMesObj.READ_STATUS['DROP']}\'," \
                      f" `reply_time`=\'{current_time}\'" \
                      f" WHERE `id` = \'{id}\'"
        self.conn.sql_commit(execute_SQL)
        return {"code": 200, "data": None}

    def reply_message(self, subject):
        try:
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            execute_sql = f" UPDATE `mem_subject_advice` SET `res`= {subject.message}, " \
                          f" `status` = \'{SubjectMesObj.READ_STATUS['READ']}\'," \
                          f" `reply_time` = {current_time}" \
                          " WHERE `id` = %d " % subject.id
            self.conn.sql_commit(execute_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def count_one(self, id) -> bool:
        fetch_sql = f"SELECT count(`id`) FROM `mem_subject_advice` WHERE 1 = 1 " \
                    f" AND `id` = \'{id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                return items[0][0] > 0
            return False
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}